package org.qpcr.community.project.web.excel;

import lombok.Getter;
import org.hswebframework.web.authorization.Authentication;
import org.hswebframework.web.validator.ValidatorUtils;
import org.qpcr.community.io.excel.AbstractImporter;
import org.qpcr.community.io.excel.ImportHelper;
import org.qpcr.community.io.file.FileManager;
import org.qpcr.community.project.model.entity.TemperatureControlEntity;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 控温算法导入.
 *
 * @author yanss 2024/6/13
 * @since 2.1
 */
public class TemperatureControlExcelImporter extends AbstractImporter<TemperatureControlExcelInfo> {

    @Getter
    private final List<TemperatureControlEntity> temperatureControlInstanceList;

    private final Authentication auth;

    public TemperatureControlExcelImporter(FileManager fileManager,
                                           WebClient client,
                                           List<TemperatureControlEntity> temperatureControlInstanceList,
                                           Authentication auth) {
        super(fileManager, client);
        this.temperatureControlInstanceList = temperatureControlInstanceList;
        this.auth = auth;
    }

    @Override
    protected Mono<Void> handleData(Flux<TemperatureControlExcelInfo> data) {
        return data
            .doOnNext(ValidatorUtils::tryValidate)
            .map(temperatureControlExcelInfo -> temperatureControlExcelInfo.initTemperatureControlInstance(temperatureControlInstanceList, auth))
            .then();
    }

    @Override
    protected TemperatureControlExcelInfo newInstance() {
        return new TemperatureControlExcelInfo();
    }

    @Override
    protected void customImport(ImportHelper<TemperatureControlExcelInfo> helper) {
        helper.fallbackSingle(true);
    }
}
